package org.huangrui.javase.thread;

/**
 * @Author hr
 * @Create 2025-11-08 15:35
 **/
public class T05ProductorAndConsumer {
    public static void main(String[] args) {
        // 1、创建资源类对象
        Workbench workbench = new Workbench();

        // 2、创建和启动厨师线程
        new Thread("厨师") {
            @Override
            public void run() {
                while (true) {
                    workbench.make();
                }
            }
        }.start();

        // 3、创建和启动服务员线程
        new Thread("服务员") {
            @Override
            public void run() {
                while (true) {
                    workbench.eat();
                }
            }
        }.start();
    }

}

// 1、定义资源类
class Workbench {
    private static final int MAX_VALUE = 10;
    private int total;

    public synchronized void make() {
        if (total >= MAX_VALUE) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        total++;
        System.out.println(Thread.currentThread().getName() + "制作了一份快餐，现在工作台上有：" + total + "份快餐");
        this.notify();
    }

    public synchronized void eat() {
        if (total <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        total--;
        System.out.println(Thread.currentThread().getName() + "取走了一份快餐，现在工作台上有：" + total + "份快餐");
        this.notify();
    }
}